import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  GetDictionaryByDictCode,
  GetSettlementtime,
  GetOrderInformation,
  ApplyPaymentSettlementCreate,
  ApplyPaymentSettlementGetAllByPagedAndSort,
  GetHaveNotAppliedFinancingLineApprovalPurchase,
  CompleteTheProjectApprovedFinancingLine,
  SupplierEnterpriseInfoGetLockedInfo,
  CompleteTheProjectApprovedOnLine
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
export function useSupplierCreditLoan() {
  const route = useRoute()
  const lockSelId = ref()
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const DialogVisible = ref<boolean>(false);
  const RefEntryPlatform = ref()
  const loanMethod = ref([])
  const projectList = ref([])
  const numberList = ref([])
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "项目名称",
      prop: "purchaseName",
    },
    {
      label: "结算方式",
      prop: "settlementMethod",
    },
    {
      label: "结算金额（元）",
      prop: "financingAmount",
    },
    {
      label: "结算状态",
      prop: "netProfit",
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.isSettlement ? "success" : ""}>
          {
            row.isSettlement ? "已结算" : "未结算"
          }
        </el-tag>
      )
    },
  ];
  const EntryPlatform = reactive({
    type: '',
    name: '',
    endTime: '',
    loanMoney: '',
    number: '',
    selectName: '',//选择融资显示的项目名称
    financingAmount: '',//选择后联动
    financingLine: '',
    //type2的时候的id
    NumberId: '',
  })
  // 万亿 长度 14
  const rules: any = {
    type: [
      {
        required: true,
        message: '请选择结算方式',
        trigger: 'blur',
      }
    ],
    name: [
      {
        required: true,
        message: '请选择采购项目',
        trigger: 'blur',
      }
    ],
    number: [
      {
        required: true,
        message: '请选择融资额度核定申请编号',
        trigger: 'blur',
      }
    ],
    financingLine: [
      {
        required: true,
        message: '请输入融资金额',
        trigger: 'blur',
      }
    ],

  };

  function SubtimEntryPlatform(row: FormInstance | undefined) {
    //这个type可以优化一下取选项label值来判断
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = {
        planId: route.query.planId,
        taskId: route.query.taskId,
        settlementMethod: EntryPlatform.type,
        purchaseOrderId: EntryPlatform.type == '4ae6853e515f11eeba2bd08e79d50dfb' ? EntryPlatform.name : EntryPlatform.NumberId,
        settlementTime: EntryPlatform.endTime,
        settlementAmount: EntryPlatform.type == '4ae6853e515f11eeba2bd08e79d50dfb' ? Number(EntryPlatform.loanMoney) : '',
        type: EntryPlatform.type == '4ae6853e515f11eeba2bd08e79d50dfb' ? 1 : 2,
        financingLineApprovalApplicationNumber: EntryPlatform.type == '4ae6853e515f11eeba2bd08e79d50dfb' ? '' : EntryPlatform.number,
        financingLine: EntryPlatform.type == '4ae6853e515f11eeba2bd08e79d50dfb' ? '' : EntryPlatform.financingAmount,
        financingAmount: EntryPlatform.type == '4ae6853e515f11eeba2bd08e79d50dfb' ? '' : Number(EntryPlatform.financingLine),
        sEIId: lockSelId.value,
      };
      if (EntryPlatform.type == '508bbe0c515f11eeba2bd08e79d50dfb' && Number(EntryPlatform.financingLine) > Number(EntryPlatform.financingAmount)) {
        ElMessage.warning('融资金额不得大于融资额度')
        return
      }
      const res = await ApplyPaymentSettlementCreate(data);
      if (res.success) {
        ElMessage.success('订单结算申请成功！')
        CloseEntryPlatform(row);
        getList()
        getSelectList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  function CloseEntryPlatform(row: FormInstance | undefined) {
    row.resetFields();
    DialogVisible.value = false;
  }

  async function getList() {
    const res = await ApplyPaymentSettlementGetAllByPagedAndSort({
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      taskId: route.query.taskId,
      planId: route.query.planId,
      type: '',
      SEIId: sessionStorage.getItem("seiId"),
    });
    if (res.success) {
      res.data.items.forEach((item) => {
        item.purchaseName = item.purchaseName.split(";").join(",").replace(/^,/, "");
        item.settlementTime = item.settlementTime.substring(0, 10)
      })
      dataList.value = res.data.items;
      loading.value = false;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }
  //计算项目的时间和金额
  async function changeProject(item) {
    let data = qs.stringify({
      purchaseOrderId: item.projectAccountsReceivable
    })
    const res = await GetSettlementtime(data);
    if (res.success) {
      EntryPlatform.endTime = res.data.substring(0, 10)
    } else {
      ElMessage.error(res.msg);
    }
    const res1 = await GetOrderInformation(data);
    if (res1.success) {
      let sum = 0
      const arr = JSON.parse(res1.data)
      arr.forEach(item => {
        sum += item.Price * item.Quantity
      })
      EntryPlatform.loanMoney = sum
    } else {
      ElMessage.error(res1.msg);
    }
  }

  async function changeNumber(item) {
    EntryPlatform.NumberId = item.projectAccountsReceivable
    EntryPlatform.selectName = item.projectAccountsReceivableName.split(";").join(",").replace(/^,/, "");
    EntryPlatform.endTime = item.applicationDate.substring(0, 10)
    EntryPlatform.financingAmount = item.financingAmount
  }


  onMounted(async () => {
    getList()
    getSelectList()
    //获取项目 projectList
    //获取编号 numberList
    let data = qs.stringify({
      dictCode: 'SettlementMethod'
    })
    const res = await GetDictionaryByDictCode(data)
    if (res.success) {
      loanMethod.value = res.data
    } else {
      ElMessage.error(res.msg)
    }

    const data1 = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const res3 = await SupplierEnterpriseInfoGetLockedInfo(data1);
    if (res3.success) {
      lockSelId.value = res3.data.seiId
    } else {
      ElMessage.error(res3.msg)
    }
  })

  function handleSizeChange() {
    getList()
  }
  function handleCurrentChange() {
    getList()
  }


  async function getSelectList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const params = qs.stringify({ sEid: sessionStorage.getItem("seiId") || '' })
    //可以融资结算
    const res = await CompleteTheProjectApprovedFinancingLine(params, data)
    if (res.success) {
      numberList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
    //线上结算
    const res1 = await CompleteTheProjectApprovedOnLine(data)
    if (res1.success) {
      projectList.value = res1.data
    } else {
      ElMessage.error(res1.msg)
    }
  }

  return {
    rules,
    columns,
    loading,
    dataList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    DialogVisible,
    EntryPlatform,
    RefEntryPlatform,
    loanMethod,
    projectList,
    numberList,
    CloseEntryPlatform,
    SubtimEntryPlatform,
    changeProject,
    changeNumber,
  }
}
